package com.hoppinzq.service.http;

import com.hoppinzq.service.aop.annotation.*;
import com.hoppinzq.service.bean.*;
import com.hoppinzq.service.cache.apiCache;
import com.hoppinzq.service.dao.ManagerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import static com.hoppinzq.service.utils.HashUtil.getHexHashString;


/**
 * @author: zq
 */
@ApiServiceMapping(title = "https服务", description = "https服务",roleType = ApiServiceMapping.RoleType.RIGHT)
public class HttpsService {

    @Autowired
    private ManagerDao dao;


    @Async
    void requestUrlAdd(){
        //TODO 调用次数+1
    }

    @ApiMapping(value = "https", title = "http请求转https，GET请求", description = "http请求转https，GET请求")
    public String getHttpsGETRequest(String httpUrl,String type){
        RequestParam requestParam= (RequestParam)RequestContext.getPrincipal();
        Object user=requestParam.getUser();
        HttpRequestBean httpRequestBean=new HttpRequestBean();
        httpRequestBean.setRequest_type(type);
        httpRequestBean.setRequest_url(httpUrl);
        String proxy_rul=getHexHashString(httpUrl);
        httpRequestBean.setProxy_url(proxy_rul);
        if(user==null){
            httpRequestBean.setUser_id("-1");
        }else{
            httpRequestBean.setUser_id("1");
        }
        dao.insertRequest(httpRequestBean);
        return proxy_rul;
    }

    @ReturnTypeUseDefault
    @ApiMapping(value = "request", title = "http请求转https，GET请求", description = "http请求转https，GET请求")
    public ApiResponse httpsRequestToHttp(String httpUrl,String json){
        HttpRequestBean httpRequestBean=dao.getRequestUrl(httpUrl);
        try {
            if("GET".equals(httpRequestBean.getRequest_type())){
                URL url = new URL(httpRequestBean.getRequest_url());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                int status = connection.getResponseCode();
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                if(status==200){
                    return ApiResponse.data(content.toString());
                }else{
                    return ApiResponse.error(status,content.toString());
                }
            }else{
                try {
                    URL url = new URL(httpRequestBean.getRequest_url());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/json");
                    connection.setDoOutput(true);
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    // 设置请求体内容
                    if(json==null)json="{}";
                    //String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(json.getBytes());
                    outputStream.flush();
                    outputStream.close();
                    // 发送POST请求
                    int status = connection.getResponseCode();
                    // 读取响应内容
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuffer content = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        content.append(inputLine);
                    }
                    in.close();
                    if(status==200){
                        return ApiResponse.data(content.toString());
                    }else{
                        return ApiResponse.error(status,content.toString());
                    }
                } catch (Exception e) {
                    System.out.println("Error: " + e.getMessage());
                }
                return ApiResponse.data("这是POST请求");
            }
        } catch (Exception e) {
            return ApiResponse.error(500,e.getMessage());
        }
    }

}

